package main

import (
    "bufio"
	"bytes"
	"fmt"
	"os/exec"
)

//前一个command输出是另个命令的输入
func main() {
	//创建命令
	cmd1 := exec.Command("ps", "-ef")
	cmd2 := exec.Command("grep", "gocode")
	//创建输出管道
	stdout1, err := cmd1.StdoutPipe()
	if err != nil {
		fmt.Printf("Error:Can not obtain the stdout pipe for command:%s\n", err)
		return
	}
	if err := cmd1.Start(); err != nil {
		fmt.Printf("Error:The command can not be startup:%s\n", err)
		return
	}
	//创建带缓冲
	outputBuf1 := bufio.NewReader(stdout1)
	//创建cmd2的写入管道
	stdin2, err := cmd2.StdinPipe()
	if err != nil {
		fmt.Printf("Error: can not obtain the stdin pipe for command:%s\n", err)
		return
	}
	//写入cmd2写入管道
	outputBuf1.WriteTo(stdin2)

	var outputBuf2 bytes.Buffer
	//输出赋值到outputBuf2
	cmd2.Stdout = &outputBuf2
	if err := cmd2.Start(); err != nil {
		fmt.Printf("Error: The command can not be startup:%s\n", err)
	}
	//关闭输入管道
	err = stdin2.Close()
	if err != nil {
		fmt.Printf("Error:Can not close the stdio pipe :%s\n", err)
		return
	}
	//等待命令完全结束
	if err := cmd2.Wait(); err != nil {
		fmt.Printf("Error:Can not wait for the command:%s\n", err)
		return
	}

	fmt.Printf("%s\n", outputBuf2.String())

}